﻿using System;
using System.ComponentModel.Composition;
using System.Reactive.Linq;
using Caliburn.Micro;
using CardPlay.Model;
using CardPlay.Model.GameModel;

namespace CardPlay.Client.ViewModels
{
    [Export(typeof(GamePreviewViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
    public sealed class GamePreviewViewModel : PropertyChangedBase, IDisposable
    {
        private IGameDescriptor _selectedGame;
        private IDisposable _loader;
        private object _gameVisual;

        [Import(RequiredCreationPolicy = CreationPolicy.NonShared)]
        public IRandomNumberSequence RandomSeries { get; set; }

        public IGameDescriptor SelectedGame
        {
            get { return _selectedGame; }

            set
            {
                if (_selectedGame == value) return;

                _selectedGame = value;
                NotifyOfPropertyChange(() => SelectedGame);

#if ! SILVERLIGHT
                CancelCreateVisual();
                GameVisual = null;

                _loader = Observable.Start(() =>
                {
                    RandomSeries.Seed = 123345344;
                    return GameViewModel.Create(SelectedGame, RandomSeries);
                }).SubscribeOnDispatcher().Subscribe(vm => { GameVisual = vm; });
#endif
            }
        }

        public object GameVisual
        {
            get { return _gameVisual; }
            set
            {
                _gameVisual = value;
                NotifyOfPropertyChange(() => GameVisual);
            }
        }

        void IDisposable.Dispose()
        {
            CancelCreateVisual();
        }

        private void CancelCreateVisual()
        {
            if (_loader == null) return;
            _loader.Dispose();
            _loader = null;
        }
    }
}